import hashlib
from decimal import Decimal
import time
from Puer.publicUtils.public_method import payment_interface
from xml.etree import ElementTree as ET
from django.db.models import F
from django.db import transaction
import urllib.request
import random
import string
import os
from django.db.models import Q
from django.shortcuts import render
from django.http import HttpResponse
from Puer.publicUtils.public_method import get_page_start_end
from models import *
from Puer.constant import constant
import json
import traceback
import datetime
from django.db import transaction
import re


# 登陆
def login(request):
    get_code = request.GET.get('js_code')
    try:
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' \
              % (constant.APP_ID, constant.SECRET, get_code)
        req = urllib.request.urlopen(url)

        json_data = eval(req.read().decode("utf8"))
        check = Users.objects.filter(userid=json_data['openid'])
        if len(check) == 0:
            # 生成6位随即邀请码
            invite_code = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6))
            # 检查邀请码唯一
            while len(Users.objects.filter(usercode=invite_code)):
                invite_code = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6))
            # 创建用户
            # 用户编号 取最大编号+1
            get_top_no = Users.objects.all().order_by('-userno')
            if len(get_top_no) == 0:
                new_no = 10000
            else:
                new_no = int(get_top_no[0].userno) + 1
            with transaction.atomic():
                user_result = Users.objects.create(userid=json_data['openid'], userno=new_no, uservip=0,
                                                   usercode=invite_code,
                                                   userscore=0)
                # 用户钱包
                Userwallet.objects.create(userid=json_data['openid'], money=0, available=0, presented=0, remark=0)
            # # 用户进度记录
            # Userprocess.objects.create(userid=jsonData['openid'], process=0, datetime=datetime.datetime.now())
            # # 用户id,是否注册,是否vip,是否有未完成订单,电话号码,会员到期是否有未完成订单
            data = [user_result.userid]

        else:
            data = [json_data['openid']]

        return HttpResponse(json.dumps(data), content_type='application/json')
    except Exception as e:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 展示钱包
def wallet(request):
    get_user_id = request.GET.get('userId')
    try:
        user_wallet = Userwallet.objects.get(userid=get_user_id)
        user = Users.objects.get(userid=get_user_id)

        data = {
            'available_balance': user_wallet.available,
            'all_balance': user_wallet.money,
            'presented_balance': user_wallet.presented,
            'score': user.userscore
        }
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 用户邀请
def invite_user(request):
    get_user_id = request.GET.get('userId')
    get_invite_code = request.GET.get('inviteCode', None)
    status = constant.NO
    try:
        if Userinvite.objects.filter(userid=get_user_id):
            status = constant.YES
        if get_invite_code:
            user = Users.objects.get(usercode=get_invite_code)
            user_id = user.userid
            Userinvite.objects.create(
                userid=get_user_id,
                inviteid=user_id,
                date=datetime.datetime.now()
            )
            return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
        inviteld_list = Userinvite.objects.filter(inviteid=get_user_id)
        user = Users.objects.get(userid=get_user_id)

        data = {
            'code': user.usercode,
            'invite': len(inviteld_list),
            'status': status
        }
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 消费明细
def pay_detail(request):
    get_user_id = request.GET.get('userId')
    try:
        data = []
        wallet_detail_res = Walletdetail.objects.filter(userid=get_user_id).order_by("-date")
        for wallte_detail in wallet_detail_res:
            data.append({
                "amount": wallte_detail.money,
                "data": wallte_detail.date.strftime("%Y-%m-%d-%H-%M-%S"),
                "kind": constant.PAYMENT_ACTION if wallte_detail.kind == constant.RECHARGE else constant.PAYMENT_BUY
            })

    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 地址管理
def show_address(request):
    get_user_id = request.GET.get('userId')

    try:
        user_address = Useraddress.objects.filter(userid=get_user_id, status=constant.USE)
        data = []
        for address in user_address:
            dic = {
                # 姓名
                'name': address.name,
                # 电话
                'phone': address.phone,
                # 地区
                'city': address.city,
                # 地址
                'address': address.address,
                # 地址id
                'address_id': address.addressid,
                # 是否默认
                'address_default': address.addressdefault
            }
            data.append(dic)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


#  添加地址
def add_address(request):
    get_user_id = request.GET.get('userId')
    get_name = request.GET.get('name')
    get_phone = request.GET.get('phone')
    get_address = request.GET.get('address')
    get_isdefault = int(request.GET.get('isDefault'))
    get_zipcode = request.GET.get('zipCode')
    get_city = request.GET.get('city')
    try:
        with transaction.atomic():
            if get_isdefault:
                Useraddress.objects.filter(userid=get_user_id, addressdefault=1, status=1).update(addressdefault=0)
            else:
                user_address_result = Useraddress.objects.filter(userid=get_user_id, status=1, addressdefault=1)

                if not user_address_result:
                    get_isdefault = 1
            user_address = Useraddress()
            user_address.userid = get_user_id
            user_address.name = get_name
            user_address.phone = get_phone
            if get_zipcode:
                user_address.zipcode = get_zipcode
            user_address.city = get_city
            user_address.addressdefault = int(get_isdefault)
            user_address.status = constant.USE
            user_address.address = get_address
            user_address.save()
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)


# 设为默认
def change_default(request):
    get_user_id = request.GET.get('userId')
    get_address_id = int(request.GET.get('addressId'))
    try:
        user_address = Useraddress.objects.filter(userid=get_user_id, status=constant.USE)
        for address in user_address:
            if address.addressid == get_address_id:
                Useraddress.objects.filter(addressid=address.addressid).update(addressdefault=constant.YES)
            else:
                Useraddress.objects.filter(addressid=address.addressid).update(addressdefault=constant.NO)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)


# 删除地址
def delete_address(request):
    get_user_id = request.GET.get('userId')
    get_address_id = request.GET.get('addressId')
    try:
        Useraddress.objects.filter(
            userid=get_user_id,
            addressid=int(get_address_id),
            status=constant.USE
        ).update(status=constant.DELETE)

    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

    return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)


#  修改地址
def update_address(request):
    get_user_id = request.GET.get('userId')
    get_address_id = request.GET.get('addressId')
    get_name = request.GET.get('name')
    get_phone = request.GET.get('phone')
    get_address = request.GET.get('address')
    get_city = request.GET.get('city')
    get_isdefault = int(request.GET.get('isDefault'))
    try:
        if get_isdefault:
            Useraddress.objects.filter(
                addressid=int(get_address_id),
                userid=get_user_id,
                status=constant.USE
            ).update(
                name=get_name,
                phone=get_phone,
                address=get_address,
                city=get_city,
                addressdefault=int(get_isdefault)
            )
            Useraddress.objects.filter(
                ~Q(addressid=int(get_address_id)),
                userid=get_user_id,
                status=constant.USE).update(
                addressdefault=constant.NO
            )
        else:
            Useraddress.objects.filter(
                addressid=int(get_address_id),
                userid=get_user_id,
                status=constant.USE
            ).update(
                name=get_name,
                phone=get_phone,
                city=get_city,
                address=get_address,
                addressdefault=int(get_isdefault)
            )
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

    return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)


# 提现审核
def auditln_advance(request):
    get_user_id = request.GET.get('userId')
    get_money = request.GET.get('money')
    try:
        Userrefund.objects.create(
            userid=get_user_id,
            datetime=datetime.datetime.now(),
            money=int(get_money),
            status=constant.WAITGO
        )
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

    return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)


# 查看提现状态
def show_advance(request):
    get_user_id = request.GET.get('userId')
    try:
        user_fund = Userrefund.objects.filter(userid=get_user_id)
        data = []
        li = ['待审核', '通过', '拒绝']
        for fund in user_fund:
            dic = {
                # 时间
                'datatime': fund.datetime.strftime("%Y-%m-%d %H:%M:%S"),
                # 金额
                'money': fund.money,
                # 状态
                'status': li[fund.status - 1]
            }
            data.append(dic)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 门店请求
def shop(request):
    try:
        stores = Store.objects.all()
        data = []
        for store in stores:
            dic = {
                'store_id': store.storeid,
                'name': store.name,
                'content': store.content,
                'address': store.address,
                'BusinessHours': store.businesshours,
                'phone': store.phone,
                'photo': '%s%s' % (constant.FILE_ADDRESS, store.photo)
            }
            data.append(dic)

    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)

    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 发送验证码
def send_message(request):
    try:
        get_phone = request.GET.get('phone')
        get_code = request.GET.get('code')
        try:
            current_path = os.path.abspath('.')
            command = "python %s/dysms_python/demo_sms_send.py %s %s" % (current_path, get_phone, str(get_code))

            os.system(command)
        except Exception:
            raise Exception("failure")
        return HttpResponse(json.dumps("success"), content_type='application/json')
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 短信验证码校验
def verification_code_verify(request):
    try:
        user_id = request.GET.get("userId")
        uesr_phone = request.GET.get("phone")
        Users.objects.filter(userid=user_id).update(userphone=uesr_phone)
        return HttpResponse('success')
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 充值支付
def charge_pay(request):
    try:
        total_fee = int(float(request.GET.get("total_fee")) * 100)
        openid = request.GET.get("userId")
        get_money = int(float(request.GET.get("total_fee")) * 100)
        data = {
            "user_id": openid,
            "client_ip": request.META.get('REMOTE_ADDR'),
            "money": total_fee,
            "body": constant.PAYMENT_ACTION
        }
        response, is_success = payment_interface(data)

        if is_success:
            new_pay = Payorders.objects.create(
                payorderid=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"),
                userid=openid,
                money=float(get_money / 100),
                date=datetime.datetime.now(),
                paykind=constant.PAYRECHARGE,
                status=constant.WAIT,
                payway=constant.PAYMENT_KIND
            )
            response["Id"] = new_pay.payorderid
        else:
            response = ["failure", "Error msg: %s" % response.get('return_msg')]

        return HttpResponse(json.dumps(response))
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 充值支付完成
def charge_pay_finish(request):
    try:
        # 用户id
        get_user = request.GET.get("userId")
        # 支付id
        get_id = request.GET.get('Id')

        jsons = "success"
        # 支付标识，0代表失败，1代表成功
        get_flag = int(request.GET.get('Flag'))

        if get_flag:

            # 支付成功
            with transaction.atomic():
                Users.objects.filter(userid=get_user).update(uservip=constant.VIPNUM)
                pay_orders_obj = Payorders.objects.get(payorderid=get_id, status=constant.WAIT)
                pay_orders_obj.status = constant.SUCCESS
                pay_orders_obj.save()
                # 充值金额
                recharge_amount = float("%.2f" % pay_orders_obj.money)
                print(recharge_amount)
                # 赠送金额
                presented = 0
                if 5000.00 < recharge_amount < 10000.00:
                    presented = 2000
                elif 10000.00 < recharge_amount < 20000.00:
                    presented = 5000
                elif recharge_amount > 20000.00:
                    presented = 10000
                print(float(presented))
                user_wallet = Userwallet.objects.filter(userid=get_user)
                if user_wallet:
                    user_wallet[0].money = Decimal(str(user_wallet[0].money)) + Decimal(str(recharge_amount)) + Decimal(
                        str(presented))
                    user_wallet[0].available = Decimal(str(user_wallet[0].available)) + Decimal(str(recharge_amount))
                    user_wallet[0].presented = Decimal(str(user_wallet[0].presented)) + Decimal(str(presented))
                    user_wallet[0].save()
                # 生成充值记录
                Walletdetail.objects.create(userid=get_user, money=recharge_amount, date=datetime.datetime.now(),
                                            kind=constant.RECHARGE)
            return HttpResponse(json.dumps(jsons), content_type='application/json')
        else:
            Payorders.objects.filter(payorderid=get_id, status=constant.WAIT).update(status=constant.FAIL)
            # 支付失败或取消,关闭订单
            data = {}
            # 小程序appId
            wx_appid = 'wx0a73c09e45cfeb1f'
            # 支付商户号
            wx_mch_id = '1509037691'
            data['appid'] = 'wx0a73c09e45cfeb1f'
            data['mch_id'] = '1509037691'
            data['out_trade_no'] = get_id
            data['nonce_str'] = ''.join(
                [(string.ascii_letters + string.digits)[x] for x in random.sample(range(0, 62), 20)])
            count = 1
            test = ""
            for i in sorted(data.keys()):
                v = data.get(i)
                if count == 1:
                    test = test + '{key}={value}'.format(key=i, value=v)
                else:
                    test = test + '&{key}={value}'.format(key=i, value=v)
                count = count + 1
            test = test + '&key=Ydx20180818Ruitakesi17610106050X'
            sign = hashlib.md5(test.encode('utf-8')).hexdigest().upper()
            data['sign'] = sign
            xml = []
            for k in sorted(data.keys()):
                v = data.get(k)
                if k == 'detail' and not v.startswith('<![CDATA['):
                    v = '<![CDATA[{}]]'.format(v)
                xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
            get_data = '<xml>{}</xml>'.format(''.join(xml))

            req = urllib.request.Request('https://api.mch.weixin.qq.com/pay/closeorder')

            with urllib.request.urlopen(req, data=get_data.encode('utf-8')) as response:
                html = response.read().decode("utf8")
                response.close()
            tree = ET.fromstring(html)
            result = {}
            if tree.tag == 'xml':
                for child in tree:
                    result[child.tag] = child.text
            if result['return_code'] == 'SUCCESS' and result['result_code'] == 'SUCCESS':
                # 关闭成功

                pass
            else:
                # 关闭失败
                jsons = 'failure'

        return HttpResponse(jsons)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 商品购买_微信支付
def purchase_of_goods(request):
    try:
        user_id = request.GET.get("userId")
        money = int(float(request.GET.get("total_fee")) * 100)

        data = {
            "user_id": user_id,
            "client_ip": request.META.get('REMOTE_ADDR'),
            "money": money,
            "body": constant.PAYMENT_BUY
        }
        response, is_success = payment_interface(data)
        if is_success:
            new_pay = Payorders.objects.create(
                payorderid=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"),
                userid=user_id,
                money=float(money / 100),
                date=datetime.datetime.now(),
                paykind=constant.BUY,
                status=constant.WAIT,
                payway=constant.PAYMENT_KIND
            )
            response["Id"] = new_pay.payorderid
        else:
            response = ["failure", "Payment failed"]
        return HttpResponse(json.dumps(response))
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 商品购买_支付成功
def products_wechat_finish(request):
    try:
        # 用户id
        user_id = request.GET.get("userId")
        # 支付id
        pay_order_id = request.GET.get('Id')
        # 支付标识，0代表失败，1代表成功
        get_flag = int(json.loads(request.GET.get('Flag')))

        order_info = json.loads(request.GET.get("orderDetail"))

        cart_id_list = order_info.get("cartId")

        # 用户实际消费金额
        consumption_amount = int(float(order_info['Money']) * 100)
        # 用户消耗积分
        score = order_info.get("score", 0)

        address_id = order_info.get("addressId")

        product_info_list = order_info.get("goodList", [])

        res = "success"

        if get_flag:
            with transaction.atomic():
                # 更新用户支付账单状态
                Payorders.objects.filter(payorderid=pay_order_id).update(status=constant.SUCCESS)
                # 更新用户积分
                if score:
                    user_obj = Users.objects.get(userid=user_id)
                    user_obj.userscore = user_obj.userscore - score
                    if user_obj.userscore < 0:
                        raise Exception("user score insufficient")
                    user_obj.save()
                # 在购物车中删除此次购买的商品
                if cart_id_list:
                    for cart_id in cart_id_list:
                        Shoppingcart.objects.filter(cartid=int(cart_id), userid=user_id).delete()

                # 创建消费明细
                Walletdetail.objects.create(userid=user_id, money=float(consumption_amount / 100),
                                            date=datetime.datetime.now(),
                                            kind=constant.CONSUME)
                # 创建商品订单信息
                order_id = "%s%s" % (datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), user_id)
                user_address_obj = Useraddress.objects.get(addressid=address_id, status=constant.USE)
                order_date = datetime.datetime.now()
                product_num_list = [int(product.get("number")) for product in product_info_list]
                products_list = [product.get("productId") for product in product_info_list]
                product_name_list = [Product.objects.get(productid=product_id).name for product_id in products_list]
                Orders.objects.create(orderid=order_id, userid=user_id, addressid=address_id,
                                      phone=user_address_obj.phone,
                                      name=user_address_obj.name, date=order_date, status=constant.OVERHANG,
                                      productname="/".join(product_name_list), number=sum(product_num_list))
                # 二级用户积分兑换
                user_invite_result = Userinvite.objects.filter(userid=user_id)
                for user_invite in user_invite_result:
                    if user_invite.inviteid:
                        socre = int((consumption_amount * 0.1) / 100)
                        Users.objects.filter(userid=user_invite.inviteid).update(userscore=F('userscore') + socre)
                # 生成订单关联
                with transaction.atomic():
                    for product in product_info_list:
                        # product_standard_obj = Productstandard.objects.get(color=product.get("color"),
                        #                                                    name=product.get("size"))
                        # product_num = int(product.get("number"))
                        # if product_standard_obj.stock < product_num:
                        #     raise Exception("product stock insufficient")
                        # # 更新商品库存
                        # product_standard_obj.stock = int(product_standard_obj.stock) - product_num
                        #
                        # product_standard_obj.save()
                        Orderdetail.objects.create(orderid=order_id, productid=product.get("productId"),
                                                   number=product.get("number"))
                        # standardid=product_standard_obj.standardid)
                return HttpResponse(res)
        else:
            Payorders.objects.filter(payorderid=pay_order_id).update(status=constant.FAIL)
            # 支付失败或取消,关闭订单
            data = {}
            # 小程序appId
            wx_appid = 'wx0a73c09e45cfeb1f'
            # 支付商户号
            wx_mch_id = '1509037691'
            data['appid'] = 'wx0a73c09e45cfeb1f'
            data['mch_id'] = '1509037691'
            data['out_trade_no'] = pay_order_id
            data['nonce_str'] = ''.join(
                [(string.ascii_letters + string.digits)[x] for x in random.sample(range(0, 62), 20)])
            count = 1
            test = ""
            for i in sorted(data.keys()):
                v = data.get(i)
                if count == 1:
                    test = test + '{key}={value}'.format(key=i, value=v)
                else:
                    test = test + '&{key}={value}'.format(key=i, value=v)
                count = count + 1
            test = test + '&key=Ydx20180818Ruitakesi17610106050X'
            sign = hashlib.md5(test.encode('utf-8')).hexdigest().upper()
            data['sign'] = sign
            xml = []
            for k in sorted(data.keys()):
                v = data.get(k)
                if k == 'detail' and not v.startswith('<![CDATA['):
                    v = '<![CDATA[{}]]'.format(v)
                xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
            get_data = '<xml>{}</xml>'.format(''.join(xml))

            req = urllib.request.Request('https://api.mch.weixin.qq.com/pay/closeorder')

            with urllib.request.urlopen(req, data=get_data.encode('utf-8')) as response:
                html = response.read().decode("utf8")
                response.close()
            tree = ET.fromstring(html)
            result = {}
            if tree.tag == 'xml':
                for child in tree:
                    result[child.tag] = child.text
            if result['return_code'] == 'SUCCESS' and result['result_code'] == 'SUCCESS':
                # 关闭成功
                res = "close order success"
            else:
                # 关闭失败
                res = 'close order failure'

    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 余额支付
def balance_payment(request):
    try:
        # 用户id
        user_id = request.GET.get("userId")
        order_info = json.loads(request.GET.get("orderDetail"))
        # 用户消耗积分
        score = int(order_info.get("score", 0))
        # 用户实际消费金额
        consumption_amount = int(float(request.GET.get("Money", "0")) * 100)
        address_id = order_info.get("addressId")
        product_info_list = order_info.get("goodList", [])
        cart_id_list = order_info.get("cartId")
        print(order_info)
        with transaction.atomic():
            # 创建用户订单
            Payorders.objects.create(payorderid=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"),
                                     userid=user_id,
                                     money=float(consumption_amount / 100),
                                     date=datetime.datetime.now(),
                                     paykind=constant.BUY,
                                     status=constant.SUCCESS,
                                     payway=constant.BALANCE_PAYMENT)
            # 在购物车中删除此次购买的商品
            if cart_id_list:
                for cart_id in cart_id_list:
                    Shoppingcart.objects.filter(cartid=int(cart_id), userid=user_id).delete()
            # 更新用户积分
            if score:
                user_obj = Users.objects.get(userid=user_id)
                user_obj.userscore = user_obj.userscore - score
                if user_obj.userscore < 0:
                    raise Exception("user score insufficient")
                user_obj.save()
            # 更新用户钱包
            user_wallet_obj = Userwallet.objects.get(userid=user_id)
            available_balance = int(user_wallet_obj.available * 100)
            presented_balance = int(user_wallet_obj.presented * 100)
            if consumption_amount > (available_balance + presented_balance):
                raise Exception("user balance insufficient")
            if presented_balance >= consumption_amount:
                presented_balance = presented_balance - consumption_amount
            else:
                balance = consumption_amount - presented_balance
                presented_balance = 0
                available_balance = available_balance - balance
            user_wallet_obj.available = float(available_balance / 100)
            user_wallet_obj.presented = float(presented_balance / 100)
            user_wallet_obj.money = float(user_wallet_obj.available + user_wallet_obj.presented)
            user_wallet_obj.save()
            # 创建消费明细
            Walletdetail.objects.create(userid=user_id, money=float(consumption_amount / 100),
                                        date=datetime.datetime.now(),
                                        kind=constant.CONSUME)
            # 创建商品订单信息
            order_id = "%s%s" % (datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), user_id)
            user_address_obj = Useraddress.objects.get(addressid=address_id, status=constant.USE)
            order_date = datetime.datetime.now()
            product_num_list = [int(product.get("number")) for product in product_info_list]
            products_list = [product.get("productId") for product in product_info_list]
            product_name_list = [Product.objects.get(productid=product_id).name for product_id in products_list]
            Orders.objects.create(orderid=order_id, userid=user_id, addressid=address_id,
                                  phone=user_address_obj.phone,
                                  name=user_address_obj.name, date=order_date, status=constant.OVERHANG,
                                  productname="/".join(product_name_list), number=sum(product_num_list))
            # 二级用户积分兑换
            user_invite_result = Userinvite.objects.filter(userid=user_id)
            for user_invite in user_invite_result:
                if user_invite.inviteid:
                    socre = int((consumption_amount * 0.1) / 100)
                    Users.objects.filter(userid=user_invite.inviteid).update(userscore=F('userscore') + socre)
            # 生成订单关联
            with transaction.atomic():
                for product in product_info_list:
                    # product_standard_obj = Productstandard.objects.get(color=product.get("color"),
                    #                                                    name=product.get("size"))
                    # product_num = int(product.get("number"))
                    # if product_standard_obj.stock < product_num:
                    #     raise Exception("product stock insufficient")
                    # # 更新商品库存
                    # product_standard_obj.stock = int(product_standard_obj.stock) - product_num
                    #
                    # product_standard_obj.save()
                    Orderdetail.objects.create(orderid=order_id, productid=product.get("productId"),
                                               number=product.get("number"))
                    # standardid=product_standard_obj.standardid)
        return HttpResponse(json.dumps("success"))
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 修改个人资料
def modify_personal_information(request):
    pass


# 直接购买确认支付
def confirm_pay(request):
    try:
        data = {}
        get_user_id = request.GET.get('userId')
        user_wallet_obj = Userwallet.objects.get(userid=get_user_id)
        if user_wallet_obj:
            # 用户全部余额
            data["total_balance"] = user_wallet_obj.money
            # 用户充值余额
            data["available_balance"] = user_wallet_obj.available
            # 用户赠送余额
            data['presented_balance'] = user_wallet_obj.presented
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 购物车确认订单
def cart_confirm_pay(request):
    try:
        get_cart_id = json.loads(request.GET.get('cartId'))
        get_user_id = request.GET.get('userId')
        address = Useraddress.objects.filter(userid=get_user_id, addressdefault=constant.USE, status=constant.USE)
        user = Users.objects.get(userid=get_user_id)
        if address:
            uesr_address = '%s%s' % (address[0].city, address[0].address)
        else:
            # 用户没有默认地址的话返回地址栏中第一个地址
            address = Useraddress.objects.filter(userid=get_user_id, status=constant.USE).order_by("addressid")
            uesr_address = '%s%s' % (address[0].city, address[0].address)
        thumbnail_list = []
        for cart_id in get_cart_id:
            cart = Shoppingcart.objects.get(cartid=int(cart_id))

            # standard_id = cart.standardid
            # pro_standard = Productstandard.objects.get(standardid=standard_id)
            product = Product.objects.get(productid=cart.productid)
            # pro = Productstandard.objects.filter(name=pro_standard.name, color=pro_standard.color,
            #                                      productid=product.productid)
            # get_product_num = cart.number
            # if pro[0].stock < get_product_num:
            #     raise Exception('not have product')
            thumbnail_list.append({
                "id": cart_id,
                "pic": "%s%s" % (constant.FILE_ADDRESS, product.thumbnail)
            })
        data = {
            'address_id': address[0].addressid if address else "",
            'name': address[0].name if address else "",
            'address': uesr_address,
            'phone': address[0].phone if address else "",
            'score': user.userscore,
            'thumbnail_list': thumbnail_list
        }
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)


# 用户意见反馈
def user_opinion(request):
    try:
        uesr_id = request.GET.get("userId")
        opinion = request.GET.get("suggestion")
        Useropinion.objects.create(
            userid=uesr_id,
            opinion=opinion,
            date=datetime.datetime.now(),
            status=constant.NO,
        )
        return HttpResponse("success")
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# ------------------------------------------------------------------------PC-------------------------------------
# 账号管理
def mg_log_in_manage(request):
    try:
        get_page = request.GET.get('page')
        get_row = request.GET.get('row')

        data = []
        user_manage_result = Usermanage.objects.all().order_by("-createtime")

        start, stop = get_page_start_end(get_page, get_row, user_manage_result)
        data_count = len(user_manage_result)
        for count in range(start, stop):
            if count >= data_count:
                break

            if user_manage_result[count].userrole == 10086:
                continue
            get_role = constant.ROLE[user_manage_result[count].userrole]
            user_manage_source = user_manage_result[count].remark
            get_user_manage_info = Usermanage.objects.filter(userid=user_manage_source)
            if get_user_manage_info:
                source = get_user_manage_info[0].username,
                row = {
                    "user_id": user_manage_result[count].userid,
                    "user_name": user_manage_result[count].username,
                    'user_no': user_manage_result[count].userno,
                    "user_role": get_role,
                    "time": user_manage_result[count].createtime.strftime("%Y-%m-%d"),
                    "source": source
                }

                data.append(row)

        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 新建账号

def new_manage(request):
    try:
        # 登陆账号
        get_no = request.GET.get('userNo')
        # 登陆名
        get_name = request.GET.get('userName')
        # 密码
        get_psw = request.GET.get('password')
        # 权限
        get_role = int(request.GET.get('role'))
        # 授权账号
        get_user = int(request.GET.get('userId'))
        check_no = Usermanage.objects.filter(userno=get_no)
        # 检查登陆账号
        if check_no:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", "No", error_msg]), content_type=constant.CONTENT_TYPE)
        check_name = Usermanage.objects.filter(username=get_name)
        # 检查登陆名
        if check_name:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", "Name", error_msg]), content_type=constant.CONTENT_TYPE)

        try:
            Usermanage.objects.create(userno=get_no, username=get_name, userpassword=get_psw,
                                      userrole=get_role, remark=get_user, createtime=datetime.datetime.now())
        except:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", "error", error_msg]), content_type=constant.CONTENT_TYPE)

        return HttpResponse(json.dumps(["success", "finish"]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 用户登陆
def log_in(request):
    try:
        user_name = request.GET.get("userName")
        user_password = request.GET.get("userPassword")
        user_info = Usermanage.objects.get(userno=user_name)
        if user_info and user_info.userno == user_name and user_info.userpassword == user_password:
            # 用户信息
            user_detail = [
                # 用户id
                user_info.userid,
                # 用户权限
                user_info.userrole
            ]
            return HttpResponse(json.dumps(["success", user_detail]), content_type=constant.CONTENT_TYPE)
        return HttpResponse(json.dumps(["failure", "Username or password is incorrect"]),
                            content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 用户密码修改

def modify_user_password(request):
    try:
        user_id = request.GET.get("userId")
        user_old_pwd = request.GET.get("oldPwd")
        user_new_pwd = request.GET.get("newPwd")
        user_manage_info = Usermanage.objects.get(userid=user_id)
        if user_manage_info:
            if user_manage_info.userpassword != user_old_pwd:
                error_msg = "User password is error"
                return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
            else:
                user_manage_info.userpassword = user_new_pwd
                user_manage_info.save()
                return HttpResponse(json.dumps(["success", "finish"]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 删除账号

def del_manage(request):
    try:
        get_id = int(request.GET.get('userId'))
        try:
            Usermanage.objects.filter(~Q(userrole=1), userid=get_id).delete()
            return HttpResponse(json.dumps("success"), content_type=constant.CONTENT_TYPE)
        except:
            error_msg = "%s" % traceback.format_exc()
            return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


#  会员记录

def user_vip(request):
    try:
        get_page = request.GET.get('page')
        get_row = request.GET.get('row')
        get_phone = request.GET.get('phone', None)
        get_status = request.GET.get('status', None)

        data = []
        user_manage_result = Payorders.objects.filter(status=constant.GO).order_by("-date")
        if get_status:
            user_manage_result = Payorders.objects.filter(paykind=int(get_status), status=constant.GO).order_by("-date")

        if get_phone:
            user = Users.objects.filter(userphone__contains=get_phone)

            user_manage_result = Payorders.objects.filter(userid=user[0].userid, status=constant.GO).order_by("-date")
        if get_status and get_phone:
            user = Users.objects.get(userphone__contains=get_phone)
            user_manage_result = Payorders.objects.filter(userid=user.userid, paykind=int(get_status),
                                                          status=constant.GO).order_by("-date")

        start, stop = get_page_start_end(get_page, get_row, user_manage_result)
        data_count = len(user_manage_result)
        for count in range(start, stop):
            if count >= data_count:
                break
            user_id = user_manage_result[count].userid
            user = Users.objects.get(userid=user_id)
            way = ['消费', '充值']
            dic = {
                # 用户
                "user_id": user_id,
                # # 用户编号
                # 'user_no': user.userno,
                # 订单编号
                "order_id": user_manage_result[count].payorderid,
                # 联系方式
                "phone": user.userphone,
                # 金额
                "money": user_manage_result[count].money,
                # 支付方式
                "pay_way": user_manage_result[count].payway,
                # 下单时间
                "time": user_manage_result[count].date.strftime("%Y.%m.%d"),
                # 类型
                "type": way[user_manage_result[count].paykind - 1]
            }

            data.append(dic)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


#  退款申请展示
def show_user_refund(request):
    try:
        get_page = request.GET.get("page")
        get_row = request.GET.get("row")
        # TODO 查询条件
        get_join_us_result = Userrefund.objects.filter(status=constant.WAITGO).order_by("-datetime")

        start, stop = get_page_start_end(get_page, get_row, get_join_us_result)
        data = []
        data_count = len(get_join_us_result)
        for count in range(start, stop):
            if count >= data_count:
                break
            print(get_join_us_result[count].userid)
            user = Users.objects.get(userid=get_join_us_result[count].userid)

            row = {
                # 退款id
                'refund_id': get_join_us_result[count].refundid,
                # 用户id
                'user_id': get_join_us_result[count].userid,
                # 用户名称
                'user_name': user.username,
                # 提交时间
                'datetime': get_join_us_result[count].datetime.strftime("%Y-%m-%d %H:%M:%S"),
                # 提现金额
                'money': get_join_us_result[count].money,
                # 联系方式
                'phone': user.userphone,
            }
            data.append(row)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 退款失败
def refund_failure(request):
    try:
        get_refund_id = int(request.GET.get('refundId'))
        if not get_refund_id:
            return HttpResponse(json.dumps(["failure", 'parameter not enough']), content_type=constant.CONTENT_TYPE)

        Userrefund.objects.filter(refundid=get_refund_id, status=constant.WAITGO).update(status=constant.REFUSE)
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)

    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 通过
def refund_success(request):
    try:
        get_refund_id = int(request.GET.get('refundId'))
        if not get_refund_id:
            return HttpResponse(json.dumps(["failure", 'parameter not enough']), content_type=constant.CONTENT_TYPE)
        with transaction.atomic():
            user_refund = Userrefund.objects.filter(refundid=get_refund_id, status=constant.WAITGO).update(
                status=constant.GO)
            money = user_refund.money
            user_id = user_refund.userid
            user_wallet = Userwallet.objects.get(userid=user_id)
            user_wallet.money = user_wallet.money + money
            user_wallet.available = user_wallet.available + money
            user_wallet.save()
            return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 添加门店
def add_store(request):
    try:
        get_store_name = request.POST.get('storeName')
        get_store_content = request.POST.get('storeContent')
        get_store_address = request.POST.get('storeAddress')
        get_store_business_hours = request.POST.get('businessHour')
        get_store_phone = request.POST.get('storePhone')
        get_store_photo = request.FILES.get('storePhoto')
        store = Store()
        store.name = get_store_name
        store.content = get_store_content
        store.address = get_store_address
        store.businesshours = get_store_business_hours
        store.phone = get_store_phone
        store.photo = get_store_photo
        store.save()
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 展示门店
def show_stores(request):
    try:
        get_page = request.GET.get("page")
        get_row = request.GET.get("row")
        get_keyword = request.GET.get('keyword')
        get_store_result = Store.objects.all()

        data = []
        if get_keyword:
            get_store_result = Store.objects.filter(
                Q(name__contains=get_keyword) | Q(content__contains=get_keyword) | Q(
                    address__contains=get_keyword) | Q(phone__contains=get_keyword))
        data_count = len(get_store_result)
        start, stop = get_page_start_end(get_page, get_row, get_store_result)
        for count in range(start, stop):
            if count >= data_count:
                break
            row = {
                # 门店id
                "store_id": get_store_result[count].storeid,
                # 门店名称
                "store_name": get_store_result[count].name,
                # 门店介绍
                'store_content': get_store_result[count].content,
                # 门店地址
                'store_address': get_store_result[count].address,
                # 营业时间
                'store_time': get_store_result[count].businesshours,
                # 照片
                'store_photo': '%s%s' % (constant.FILE_ADDRESS, get_store_result[count].photo),
                # 手机号
                'store_phone': get_store_result[count].phone

            }
            data.append(row)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 删除门店
def delete_store(request):
    try:
        get_store_id = request.GET.get('storeId')
        if not get_store_id:
            return HttpResponse(json.dumps(["failure", 'no have param ']), content_type=constant.CONTENT_TYPE)
        Store.objects.filter(storeid=int(get_store_id)).delete()
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 门店详情
def store_detail(request):
    try:
        get_store_id = request.GET.get('storeId')
        if not get_store_id:
            return HttpResponse(json.dumps(["failure", 'no have param ']), content_type=constant.CONTENT_TYPE)
        store = Store.objects.get(storeid=get_store_id)
        data = {
            # 门店id
            "store_id": store.storeid,
            # 门店名称
            "store_name": store.name,
            # 门店介绍
            'store_content': store.content,
            # 门店地址
            'store_address': store.address,
            # 营业时间
            'store_time': store.businesshours,
            # 照片
            'store_photo': '%s%s' % (constant.FILE_ADDRESS, store.photo),
            # 手机号
            'store_phone': store.phone

        }
        return HttpResponse(json.dumps(data), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 展示反馈意见
def show_opinion(request):
    try:
        get_page = request.GET.get("page")
        get_row = request.GET.get("row")
        get_keyword = request.GET.get('keyword')
        get_opinion_result = Useropinion.objects.filter(status=0)

        data = []
        if get_keyword:
            get_opinion_result = Useropinion.objects.filter(status=0).filter(
                Q(userid__contains=get_keyword) | Q(opinion__contains=get_keyword))
        data_count = len(get_opinion_result)
        start, stop = get_page_start_end(get_page, get_row, get_opinion_result)
        for count in range(start, stop):
            if count >= data_count:
                break
            user = Users.objects.get(userid=get_opinion_result[count].userid)

            row = {
                # 投诉id
                'opinion_id': get_opinion_result[count].id,
                # 投诉意见
                'opinion': get_opinion_result[count].opinion,
                # 投诉时间
                'time': get_opinion_result[count].date.strftime('%Y.%m.%d'),
                # 投诉人电话
                'phone': user.userphone,
                # 投诉人名称
                'name': user.username

            }
            data.append(row)
        return HttpResponse(json.dumps([data, data_count]), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)


# 处理反馈意见

def deal_opinion(request):
    try:
        get_opinion_id = request.GET.get('opinionId')
        if not get_opinion_id:
            return HttpResponse(json.dumps(["failure", 'not have this opinion']), content_type=constant.CONTENT_TYPE)
        Useropinion.objects.filter(id=int(get_opinion_id)).update(status=1)
        return HttpResponse(json.dumps('success'), content_type=constant.CONTENT_TYPE)
    except:
        error_msg = "%s" % traceback.format_exc()
        return HttpResponse(json.dumps(["failure", error_msg]), content_type=constant.CONTENT_TYPE)
